/***************************************************
File:           LPK_MagneticField.cs
Authors:        Christopher Onorati
Last Updated:   5/20/2019
Last Version:   2018.3.14

Description:
  This component causes objects within its radius to be pulled or pushed away.

This script is a basic and generic implementation of its 
functionality. It is designed for educational purposes and 
aimed at helping beginners.

Copyright 2018-2019, DigiPen Institute of Technology
***************************************************/

using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace LPK
{

/**
* CLASS NAME  : LPK_MagneticField
* DESCRIPTION : Field which attracts or repels objects like a magnet.
**/
[RequireComponent(typeof(Transform))]
public class LPK_MagneticField : LPK_Component
{
    /************************************************************************************/

    public bool m_bConstantForce = false;
    public float m_flMagnitude = 10.0f;
    public float m_flRadius = 10.0f;

    [Tooltip("Tags that the GameObjects must have to be affected.  Using this is much less expensive.  If not set, any GameObject with a Rigidbody will be affected.")]
    [TagDropdown]
    public string[] m_SearchTags;

    /************************************************************************************/

    //NOTENOTE: How many objets to effect per frame.  The higher this is, the more expensive the effect.  Hardset to 128.
    const int m_GatherCount = 128;

    /************************************************************************************/

    Transform m_cTransform;

    /**
    * FUNCTION NAME: OnStart
    * DESCRIPTION  : Sets up event listening.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    override protected void OnStart ()
    {
        m_cTransform = GetComponent<Transform>();
    }

    /**
    * FUNCTION NAME: OnDrawGizmosSelected
    * DESCRIPTION  : Visualizer for the radius of the magnet
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.blue;
        Gizmos.DrawWireSphere(transform.position, m_flRadius);
    }

    /**
    * FUNCTION NAME: Update
    * DESCRIPTION  : Gathers a list of objects to potentially push and then does the thing.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void Update()
    {
        List<GameObject> objects = new List<GameObject>();

        //No tags set.  Select all.
        if (m_SearchTags.Length == 0)
        {
            GetGameObjectsInRadius(objects, m_flRadius, m_GatherCount);

            for (int j = 0; j < objects.Count; j++)
            {
                if (objects[j].GetComponent<Rigidbody2D>() != null)
                    PushObject(objects[j]);
            }
        }

        else
        {
            for (int i = 0; i < m_SearchTags.Length; i++)
            {
                //NOTENOTE: Technically you could just use a sphere collider for this - but the designer may want to use a sphere collider
                // for something else relevant to the gameobject, so this we instead manually grab.  More expensive but worth the cost.
                GetGameObjectsInRadius(objects, m_flRadius, m_GatherCount, m_SearchTags[i]);

                for (int j = 0; j < objects.Count; j++)
                {
                    if (objects[j].GetComponent<Rigidbody2D>() != null)
                        PushObject(objects[j]);
                }
            }
        }
	}

    /**
    * FUNCTION NAME: PushObject
    * DESCRIPTION  : Manages the pushing of detected objects.
    * INPUTS       : _target - Object to apply force to.
    * OUTPUTS      : None
    **/
    void PushObject(GameObject _target)
    {
        Rigidbody2D tarRigidBody = _target.GetComponent<Rigidbody2D>();

        if (tarRigidBody == null)
            return;

        float distanceScalar = 1.0f;

        //Set distance scalar.
        if (!m_bConstantForce)
        {
            float distance = Vector3.Distance(_target.transform.position, m_cTransform.position);
            distanceScalar = Mathf.Clamp(1.0f - (distance / m_flRadius), 0.0f, 1.0f);
        }

        Vector3 direction = _target.transform.position - m_cTransform.position;
        direction = direction.normalized;

        tarRigidBody.AddForce(m_flMagnitude * direction * distanceScalar);

        if (m_bPrintDebug)
            LPK_PrintDebug(this, "Pushing object:" + _target.name);
    }
}

#if UNITY_EDITOR

[CustomEditor(typeof(LPK_MagneticField))]
public class LPK_MagneticFieldEditor : Editor
{
    SerializedProperty searchTags;

    /**
    * FUNCTION NAME: OnEnable
    * DESCRIPTION  : Save out serialized classes.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    void OnEnable()
    {
        searchTags = serializedObject.FindProperty("m_SearchTags");
    }

    /**
    * FUNCTION NAME: OnInspectorGUI
    * DESCRIPTION  : Override GUI for inspector.
    * INPUTS       : None
    * OUTPUTS      : None
    **/
    public override void OnInspectorGUI()
    {
        LPK_MagneticField owner = (LPK_MagneticField)target;

        LPK_MagneticField editorOwner = owner.GetComponent<LPK_MagneticField>();

        EditorGUI.BeginDisabledGroup(true);
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.PrefixLabel("Script");
        editorOwner = (LPK_MagneticField)EditorGUILayout.ObjectField(editorOwner, typeof(LPK_MagneticField), false);
        GUILayout.EndHorizontal();
        EditorGUI.EndDisabledGroup();

        //Undo saving.
        Undo.RecordObject(owner, "Property changes on LPK_MagneticField");

        //Component properties.
        GUILayout.Space(10);
        EditorGUILayout.LabelField("Component Properties", EditorStyles.boldLabel);

        owner.m_bConstantForce = EditorGUILayout.Toggle(new GUIContent("Constant Force", "Set the field to apply a constant force, rather than be scaled based on distance."), owner.m_bConstantForce);
        owner.m_flMagnitude = EditorGUILayout.FloatField(new GUIContent("Magnitude", "Magnitude of the force.  Positive forces repel objects, negative forces pull objects."), owner.m_flMagnitude);
        owner.m_flRadius = EditorGUILayout.FloatField(new GUIContent("Radius", "Radius of the field."), owner.m_flRadius);
        EditorGUILayout.PropertyField(searchTags, true);

        //Debug properties.
        GUILayout.Space(10);
        EditorGUILayout.LabelField("Debug Properties", EditorStyles.boldLabel);

        owner.m_bPrintDebug = EditorGUILayout.Toggle(new GUIContent("Print Debug Info", "Toggle console debug messages."), owner.m_bPrintDebug);
        owner.m_sLabel = EditorGUILayout.TextField(new GUIContent("Label", "Notes for the user about this component.  This does nothing to the game or build."), owner.m_sLabel);

        //Apply changes.
        serializedObject.ApplyModifiedProperties();
    }
}

#endif  //UNITY_EDITOR

}   //LPK
